package cn.sc.summer.exception.config;

import cn.sc.summer.constant.model.Result;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author a-xin
 * @description 全局默认错误接口
 * @belongsProject SummerCloud
 * @belongsPackage cn.sc.summer.exception.config
 * @date 2025-02-08  14:06
 */
@RestController
public class GlobalErrorController implements ErrorController {

    private final String ERROR_PATH = "/error";

    @Resource
    private ErrorAttributes errorAttributes;

    /**
     * JSON格式错误信息
     */
    @RequestMapping(value = ERROR_PATH, produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Map<String, Object>> error(WebRequest webRequest) {
        ErrorAttributeOptions options = ErrorAttributeOptions.of(ErrorAttributeOptions.Include.MESSAGE);
        Map<String, Object> body = this.errorAttributes.getErrorAttributes(webRequest, options);
        return Result.fail(body);
    }

}
